/*INCLUDES *******************************************************************/
#include "ses/ses_alarm_clock.h"
#include "ses/ses_scheduler.h"
#include "ses/ses_button.h"
#include "ses/ses_led.h"
#include "ses/ses_wait.h"


/* DEFINES & MACROS **********************************************************/
#define HOUR_IN_MS					3600000
#define MIN_IN_MS					60000
#define SEC_IN_MS					1000
#define ALARM_COMPARE_TOLERANCE		10000


/* FUNCTION PROTOTYPES *******************************************************/
/**
 * Wrapper function for using the dispatch function with the scheduler
 */
void dispatchFsm();

/**
 * Looks for events and saves them in the pointer.
 *
 * @param the pointer to save the event
 */
void checkEvents(Event* e);


/* GLOBAL VARIABLES **********************************************************/
//The alarm clock instance
Fsm aClock_fsm;
//To save the occuring events
Event aClock_event;
//Variable to compare if a second has passed
uint8_t lastSecond;

/* FUNCTION DEFINITIONS ******************************************************/
int main() {

	lastSecond = 0;
	aClock_event.signal = NULL_EVENT;
	aClock_init(&aClock_fsm);
	led_greenOn();
/*
	type_timeRTC time;
	time.milli = 15;
	time.second = 15;
	time.minute = 15;
	time.hour = 15;
	scheduler_setTimeRTC(&time);
	displayPrint_setCursor(0,0);
	printf("%d:%d:%d:%d", time.hour, time.minute, time.second, time.minute);
	scheduler_getTimeRTC(&time);
	displayPrint_setCursor(0,2);
	printf("%d:%d:%d:%d", time.hour, time.minute, time.second, time.minute);

*/



	scheduler_add(dispatchFsm, 100);
	scheduler_run();

	return 0;
}

void dispatchFsm() {
	checkEvents(&aClock_event);
	displayPrint_setCursor(0,3);
	printf("event: %u", aClock_event.signal);
	if(aClock_event.signal != NULL_EVENT){
		aClock_dispatch(&aClock_fsm, &aClock_event);
	}
	scheduler_add(dispatchFsm, 100);
}

void checkEvents(Event* e) {
	//get the current time
	type_timeRTC time;
	scheduler_getTimeRTC(&time);

	if (time.second != lastSecond) {
		//A second has passed
		lastSecond = time.second;
		e->signal = SECOND_TIMER;
	}
	else if (button_isRotaryPressed()) {
		//Rotary is pressed
		e->signal = ROT_BUTTON;
	}
	else if (button_isJoystickPressed()) {
		//Joystick is pressed
		e->signal = JS_BUTTON;
	}
	else if (aClock_fsm.alarmSet != 0) {
		//Alarm is set, compute the difference between current time and alarm time
		double timeDiff = (aClock_fsm.timeSet - (time.hour * HOUR_IN_MS
				+ time.minute * MIN_IN_MS + time.second * SEC_IN_MS
				+ time.milli));
		//Difference is smaller than a defined value, trigger alarm
		if (timeDiff < ALARM_COMPARE_TOLERANCE) {
			e->signal = ALARM_TIMER;
		}
	}
	else {
		//Nothing special happened
		e->signal = NULL_EVENT;
	}
}
